/**
 * 
 */
(function($) {
	var privateFunction = function() {
		var defaults = { 
				inputId:"customerid_1",//隐藏输入框input的id值
				url:"./customer.do?reqCode=queryCustomerFilterList",//远程查询的url
				holder:"全部渠道",//初始化数据没有查询到数据时的提示
				msg:"没有匹配的数据",//实时过滤没有搜索到数据时的提示
				popId:"customer_1-config",//弹出model的id值
				popTableId:"customerTable_1",//弹出model的table的id值
				popSelectMore:false,//支持是否对弹出model的table多选，fasle为单选，true为多选
				modelBtnId:"btn_submit",//弹出model的"确认"或"提交"按钮的id值
				initSelection:{},//下拉框初始化数据前的一些操作（主要是一些校验，没有校验时，可以忽略）
				formatResult:{},//下拉框数据特殊展示的一些处理（例如商品需要判断有没有辅助属性，有时，需要把辅助属性也展示）
				formatSelection:{},//下拉框选中数据时的一些处理
				formatRemove:{},//删除选中数据时的一些处理
				formatOpenModel:{},
				beforeAjax:{},
				};
		return defaults;
		};

	var methods = {
		init: function(options) {
			// 在每个元素上执行方法
			var $this = $(this);
			//尝试去获取settings，如果不存在，则返回“undefined”
			var settings = $this.data('select2Api');
			// 如果获取settings失败，则根据options和default创建它
			if(typeof(settings) == 'undefined' || settings == null) {
				settings = $.extend({}, privateFunction(), options);
				// 保存我们新创建的settings
				$this.data('select2Api', settings);
			} else {
				// 如果我们获取了settings，则将它和options进行合并（这不是必须的，你可以选择不这样做）
				settings = $.extend({}, settings, options);
				// 如果你想每次都保存options，可以添加下面代码：
				// $this.data('select2Api', settings);
			}
			methods.createSelect(settings);
			methods.changehtml(settings);
		},
		createSelect:function(settings){
			$("#"+settings.inputId).select2({
		           placeholder: settings.holder,
		           minimumInputLength: 0,
		           maximumSelectionSize: 1,
		           allowClear: true,  //是否允许用户清除文本信息
		           removeinit: false,
		           ajax: { 
		               url: settings.url,
		               dataType: 'json',
		               type: "POST",
		               data: function (term, iPage) {
		            	   if(typeof(settings.beforeAjax) == 'function'){
		            		    return settings.beforeAjax(term, iPage, settings);
		            	   }else{
		            		    return {
			                       queryParam: term, 
			                       limit: 10,
			                       start: (iPage-1) * 10,
			                    };   
		            	   }
		               },
                       processResults: function (data, page) {
		            	    if(typeof(data.iTotalRecords) == 'undefined'){
		            		    data.iTotalRecords =  data.TOTALCOUNT;
		            		    data.aaData =  data.ROOT;
		            	    }
							if(data.iTotalRecords>0){
			               		var more = (page*10)<data.iTotalRecords;    //用来判断是否还有更多数据可以加载  
			               		if(more){
					                return {results:data.aaData,more:more};
			               		}else{
			               			return {results: data.aaData}; 
			               		}
			               	}else{
			               	 	return {results: data.aaData};
			               	}                	
		               }
		           },
		           initSelection: function() {  
		        	   if(typeof(settings.initSelection)!= 'function' || settings.initSelection(settings)){
		        		   return true;
		        	   }else{
		        		   return false;
		        	   }
				   },
		           formatResult: function(data) { 
		        	   if(typeof(settings.formatResult)== 'function'){
		        		   return settings.formatResult(data);
		        	   }else{
		        		   return  data.name;
		        	   }
			       }, 
		           formatSelection: function(data) {
		        	   var resultSel ;
		        	   if(typeof(settings.formatSelection)== 'object'
		        		   && typeof(settings.formatSelection.insertdata)== 'function'){
		        		    data = settings.formatSelection.insertdata(data);
		        	   }else{
		        		    data.hidedata = data.id;
		        		    data.displaydata = data.name;
		        	   }
		        	   return  methods.insert(data,settings);
		   		   },
			       formatNoMatches: function(item) {  
			           return  settings.msg;
			       },
		    	   formatSearching: function(item) {  
		        	   return  "加载数据中...";
		    	   },
	        	   dropdownCssClass: "bigdrop", 
	           	   		escapeMarkup: function (m) {
	           		   return m;
	           	   }
		    });			
		},
		changehtml:function(settings){
			var inputId = settings.inputId;
			$("#s2id_"+inputId).find(".select2-choice").removeClass("select2-default").css("padding-right","2.7em");
			$("#s2id_"+inputId).find(".select2-search-choice-close").remove();
			$("#s2id_"+inputId).find(".select2-arrow").remove();
			var div$  = document.getElementById("s2id_"+inputId);
			var child$ = div$.childNodes[1];
			var new1 = document.createElement("a");
			new1.setAttribute("id","choice-close"+inputId);
			new1.setAttribute("class","select2-search-choice-close");
			new1.setAttribute("style","right: 1.5em;top:0.7em;z-index:9990;display:none;cursor:pointer;");
			div$.insertBefore(new1,child$);
			var new2 = document.createElement("a");
			new2.setAttribute("id","model-open"+inputId);
			new2.setAttribute("class","fa fa-ellipsis-horizontal open-span");
			new2.setAttribute("style","position:relative;z-index:9990;color:black;");
			div$.insertBefore(new2,child$);
			$('#choice-close'+inputId).click(function () { 
				methods.choiceSelectClose(settings);
			});
			$('#model-open'+inputId).click(function () { 
				methods.openSelectTable(settings); 
			});				
		},
		insert:function(data,settings){
			if(data == '' || data == null){
				return '';
			}
			var inputId = '';
			if(typeof(settings) == 'string' || !settings){
				inputId = $(this).attr('id');
			}else{
				inputId = settings.inputId;
			}
			data.hidedata = data.hidedata == undefined ? '' : data.hidedata;
			data.displaydata = data.displaydata == undefined ? '' : data.displaydata;
	  		$("#"+inputId).val(data.hidedata);
	  		if(data.hidedata == '' || data.hidedata == null){
	  			$("#s2id_"+inputId).find("#choice-close"+inputId).css("display","none");
	  		}else{
	  			$("#s2id_"+inputId).find("#choice-close"+inputId).css("display","block");
	  		}
			$("#s2id_"+inputId).find(".select2-selection__rendered").html(data.displaydata);
			if(typeof(settings) == 'object' && typeof(settings.formatSelection)== 'object' 
				&& typeof(settings.formatSelection.afterinsert)== 'function' ){
				return settings.formatSelection.afterinsert(data,settings);
			}
			
			
			//var index=div$.parentElement.parentElement.id;
			var div$  = document.getElementById("s2id_"+inputId);
			//var index = div$.parentElement.parentElement.id;
			if(div$){
				var tr= div$.parentElement.parentElement;
				var nextRowQtyInput=$(tr).find("input[name=qty]");
				if(nextRowQtyInput != null){
					nextRowQtyInput.focus();
					setTimeout(function(){
						nextRowQtyInput.select();
					},100);
				}
			}
			
		},
		choiceSelectClose :function(settings) {
			var inputId = '',holder='';
			if(typeof(settings) == 'string' || !settings){
				inputId = $(this).attr('id');
				holder = settings;
			}else{
				inputId = settings.inputId;
				holder = settings.holder;
			}
			$('#select2-drop').css('display','none');
			$('#s2id_'+inputId).find('#choice-close'+inputId).css('display','none');
			$('#s2id_'+inputId).find('.select2-chosen').html(holder);
			$('#'+inputId).val('');
			if(typeof(settings) == 'object' && typeof(settings.formatRemove)== 'function'){
				return settings.formatRemove(settings);
			};
		},
		openSelectTable:function(settings) {
			if(typeof(settings)== 'object'){
				if(typeof(settings.initSelection)!= 'function' || settings.initSelection(settings)){
					$("#select2-drop").css("display","none");
					$('#'+settings.popTableId+' tr span').removeClass("checked");
					$('#'+settings.popTableId+' tr input').attr("checked", false);
					
					var $btn = $('#'+settings.popId).find("#"+settings.modelBtnId); 
					if($btn.length == 0){
						$btn = $('#'+settings.popId).find(".btnsubmit");
					}
					$btn.attr("value",settings.inputId);
					$btn.attr("more",settings.popSelectMore);
					$btn.attr("popId",settings.popId);
					$btn.attr("popTableId",settings.popTableId);
					if(typeof(settings.formatOpenModel) == 'function'){
						settings.formatOpenModel(settings);
					}
					$("#"+settings.popTableId).DataTable().fnDraw();	
					$('#'+settings.popId).modal('show');
				}
			}
		},
		popTableSelect:function(op){
			$btn = $(this);
			var inputId = $btn.attr("value"),popSelectMore = $btn.attr("more"),
			popTableId = $btn.attr("popTableId"),popId = $btn.attr("popId");
			//检查是否有被勾选的数据
			var set = jQuery(jQuery('#'+popTableId+' .group-checkable')[0]).attr("data-set");
		    var index = 0;
			var count =0;
		    jQuery(set).each(function () {
		        if(jQuery(this).is(":checked")){
		        	count++;
		        }
		    });
		    //判断是否选中了多条数据
		    if(popSelectMore=="false" && count>1){
		    	bootbox.alert("请不要选中多条数据");
		    	return false;
		    }
		    var dataTR = [];
		    if(count > 0){
			    jQuery(set).each(
						function() {
							if (jQuery(this).is(":checked")) {
								dataTR.push($('#'+popTableId+' tbody')[0].children[index]);
							}
							index++;
					});
		    }
		    $('#'+popId).modal('hide');	
		    return dataTR;
		}
		};
	
	$.fn.select2Api = function() {
		var method = arguments[0];
		if(methods[method]) {
			method = methods[method];
			arguments = Array.prototype.slice.call(arguments, 1);
		} else if( typeof(method) == 'object' || !method ) {
			method = methods.init;
		} else {
			$.error( 'Method ' +method + ' does not exist on select2Tools.do.js ' );
			return this;
		}
		return method.apply(this, arguments);
	};
})(jQuery);

function doRepeatItem(inputId,value,holder){
	if(value != ''){
		$("#s2id_"+inputId).find(".select2-chosen").html(value);
	}else{
		$("#s2id_"+inputId).find(".select2-chosen").html(holder);
		$("#s2id_"+inputId).find(".select2-search-choice-close").css("display","none");
	}
}